import { Menu, message } from 'antd'
import { Link } from 'react-router-dom'
import { useSelector } from 'react-redux'
import { isAuth } from '../../helpers/auth'
import axios from 'axios'
import {push} from 'connected-react-router'
import { API } from '../../config'
import { useDispatch } from 'react-redux'
function Navgation() {
  const router = useSelector(state => state.router.location.pathname)
  const auth = isAuth()
  const dispatch = useDispatch()
  const hanlerSignout = ()=>{
    axios.get(`${API}/signout`)
    localStorage.removeItem('jwt')
    message.success('退出登录成功！')
    dispatch(push('/'))
  }
  const showAuth = () => (
    <>
      <Menu.Item key="/signin">
        <Link to="/signin">登录</Link>
      </Menu.Item>
      <Menu.Item key="/signup">
        <Link to="/signup">注册</Link>
      </Menu.Item>
    </>
  )
  const showDashboard = () => {
    console.log(auth)
    const url = auth.user.role === 1 ? '/admin/dashboard' : '/user/dashboard'
    return (
      <>
        <Menu.Item key={url}>
          <Link to={url}>{auth.user.name},欢迎光临！</Link>
        </Menu.Item>
        <Menu.Item onClick={hanlerSignout}>
          退出
        </Menu.Item>
      </>

    )
  }
  return (
    <Menu mode="horizontal" selectedKeys={[router]}>
      <Menu.Item key="/">
        <Link to="/">首页</Link>
      </Menu.Item>
      <Menu.Item key="/shop">
        <Link to="/shop">商城</Link>
      </Menu.Item>
      {
        auth ? showDashboard() : showAuth()
      }
      <Menu.Item key="/cart">
        <Link to="/cart">购物车</Link>
      </Menu.Item>

    </Menu>
  )
}

export default Navgation